﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace Common.DLR
{
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ListSerializer<T>
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string SerializeGenericListObjAsXml(List<T> value)
        {
            ListArrayConverter<T> lac = new ListArrayConverter<T>();
            T[] array = lac.ToArray(value);
            string strVal = string.Empty;
            XmlSerializer serializer = new XmlSerializer(array.GetType());
            StringBuilder buffer = new StringBuilder();
            StringWriter sWriter = new StringWriter(buffer);
            serializer.Serialize(sWriter, array);
            sWriter.Flush();
            strVal = buffer.ToString();
            return strVal;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public List<T> InstantiateGenericListObjFromXml(string value)
        {
            ListArrayConverter<T> lac=new ListArrayConverter<T>();
            XmlSerializer serializer = new XmlSerializer(typeof(T[]));
            StringReader sReader = new StringReader(value);
            object objVal = serializer.Deserialize(sReader);
            T[] objArray = (T[]) objVal;
            return lac.ToList(objArray);
        }
    }
}
